package com.dhcc.cdc.busi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.dao.*;
import com.dhcc.cdc.busi.entity.*;
import com.dhcc.cdc.busi.service.ICdcDiagnosisService;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.sys.dao.CdcDataMapper;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 诊断表数据服务层接口
 * 
 * @ClassName: CdcDiagnosisServiceImpl
 * @Description: TODO
 * @author jumper
 * @date 2021-03-15 10:20:08
 */
@Service("cdcDiagnosisService")
public class CdcDiagnosisServiceImpl extends BaseServiceImpl<CdcDiagnosisMapper, CdcDiagnosisEntity> implements ICdcDiagnosisService {

	@Autowired
	private ICdcDictionaryService cdcDictionaryService;
	
	@Autowired
	private CdcEpisodeMapper cdcEpisodeMapper;
	
	@Autowired
	private CdcDictypeMapper cdcDictypeMapper;
	
	@Autowired
    private CdcDictionaryMapper cdcDictionaryMapper;
	
	@Autowired
	private CdcUserMapper cdcUserMapper;
	
	@Autowired
	private CdcDataMapper cdcDataMapper;

	@Override
	public List<CdcDiagnosisEntity> page(Page<CdcDiagnosisEntity> page, Map<String, Object> map) {
		return this.baseMapper.page(page, map);
	}
	@Override
	public List<CdcDiagnosisEntity> list(Map<String, Object> map) {
		return this.baseMapper.list(map);
	}

	@Override
	public List<CdcDiagnosisEntity> selectIcd10ByEpisode(Long aEpisodeID, String diagSource, String diagType) {
		List<CdcDiagnosisEntity> res = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		map.put("episodeId", aEpisodeID);
		List<CdcDiagnosisEntity> list = this.list(map);
		//查询所有
		for (CdcDiagnosisEntity cdcDiagnosisEntity : list){
			CdcDictionaryEntity cdcDictionaryEntity = cdcDictionaryService.selectById(cdcDiagnosisEntity.getBusDiagSourceId());
			if (Objects.equals(diagSource, cdcDictionaryEntity.getCode())){
				CdcDictionaryEntity cdcDictionaryEntity1 = cdcDictionaryService.selectById(cdcDiagnosisEntity.getBusDiagTypeId());
				if (Objects.equals(diagType, cdcDictionaryEntity1.getCode())){
					res.add(cdcDiagnosisEntity);
				}
			}
		}
		return res;
	}
	/**
	 * 
	 * <p>Title: handleXmlData</p>   
	 * <p>Description: </p>   
	 * @param dataStr
	 * @return   
	 * @see com.dhcc.cdc.busi.service.ICdcDiagnosisService#handleXmlData(java.lang.String)   
	 *
	 */
	@Override
	public String handleXmlData(String dataStr) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Document doc = null;
        try {
            doc = DocumentHelper.parseText(dataStr); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            Iterator<Element> iter = rootElt.elementIterator("diagnosis"); // 获取根节点下的子节点diagnosis
            // 遍历diagnosis节点
            while (iter.hasNext()) {
                Element diagEle = iter.next();
                String xcode= diagEle.elementTextTrim("xcode"); //唯一标识
                String episodeid= diagEle.elementTextTrim("episodeid"); //就诊记录
                String busdiagcatecode= diagEle.elementTextTrim("busdiagcatecode"); //分类代码
                String busdiagcatedesc= diagEle.elementTextTrim("busdiagcatedesc"); //分类描述
                String busdiagtypecode= diagEle.elementTextTrim("busdiagtypecode"); //类型代码
                String busdiagtypedesc= diagEle.elementTextTrim("busdiagtypedesc"); //类型描述
                String description= diagEle.elementTextTrim("description"); //描述
                String icd10= diagEle.elementTextTrim("icd10"); //ICD10
                String ismainstr= diagEle.elementTextTrim("ismain"); //是否主诊断
                String busdiagstatuscode= diagEle.elementTextTrim("busdiagstatuscode"); //状态代码
                String busdiagstatusdesc= diagEle.elementTextTrim("busdiagstatusdesc"); //状态描述
                String diagdatestr= diagEle.elementTextTrim("diagdate"); //诊断日期
                String attackdatestr= diagEle.elementTextTrim("attackdate"); //发病日期
                String busdiagsourcecode= diagEle.elementTextTrim("busdiagsourcecode"); //来源代码
                String busdiagsourcedesc= diagEle.elementTextTrim("busdiagsourcedesc"); //来源描述
                String note= diagEle.elementTextTrim("note"); //备注
                String updatetimestr= diagEle.elementTextTrim("updatetime"); //更新时间
                String updateuserid= diagEle.elementTextTrim("updateuserid"); //更新人
                String opercode= diagEle.elementTextTrim("opercode"); //操作码
                CdcDiagnosisEntity diag = new CdcDiagnosisEntity();
                diag.setXcode(xcode);
                //获取dataid
            	CdcDataEntity cdcDataEntity = new CdcDataEntity();
            	cdcDataEntity.setCode("DiagData");
            	cdcDataEntity.setIsActive(1);
            	cdcDataEntity = cdcDataMapper.selectOne(cdcDataEntity);
        		Long dataId = cdcDataEntity.getId();
                //获取basedataId
    			CdcDataEntity cdcDataEntityBase = new CdcDataEntity();
    			cdcDataEntityBase.setCode("HisBase");
    			cdcDataEntityBase.setIsActive(1);
    			cdcDataEntityBase = cdcDataMapper.selectOne(cdcDataEntityBase);
        		Long basedataId = cdcDataEntityBase.getId();
                if(CommonUtil.isNotEmpty(updatetimestr)) {
            		Date updatetime = sdf.parse(updatetimestr);
            		diag.setUpdateDate(updatetime);
            	}
            	//获取更新人
            	if(CommonUtil.isNotEmpty(updateuserid)) {
            		CdcUserEntity cdcUserEntity = new CdcUserEntity();
            		cdcUserEntity.setXcode(updateuserid);
            		cdcUserEntity.setDataId(basedataId);
            		cdcUserEntity.setIsActive(1);
            		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
            		//判断人员存在不存在
            		Long updateuser = null;
            		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
            			cdcUserEntity = new CdcUserEntity();
            			cdcUserEntity.setXcode(updateuserid);
                		cdcUserEntity.setIsActive(1);
            			cdcUserEntity.setCode("newuser"+updateuserid);
            			cdcUserEntity.setName("newuser"+updateuserid);
                		cdcUserEntity.setDataId(basedataId);
                		//保存用户
                		cdcUserMapper.insert(cdcUserEntity);
                		updateuser = cdcUserEntity.getId();
            		}else {
            			updateuser = cdcUserEntity.getId();
            		}
            		diag.setUpdateBy(updateuser);
            	}
                if("1".equals(opercode)) {//保存/修改
                	//获取episodeid
                	CdcEpisodeEntity cdcEpisodeEntity = new CdcEpisodeEntity();
                	cdcEpisodeEntity.setXcode(episodeid);
                	cdcEpisodeEntity=cdcEpisodeMapper.selectOne(cdcEpisodeEntity);//就诊信息没在库中？？？
                	Long epsid = cdcEpisodeEntity.getId();
                	diag.setEpisodeId(epsid);
                	                	
                	//获取DiagCateId
                	if(CommonUtil.isNotEmpty(busdiagcatecode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                    	cdcDictypeEntity.setCode("bus_diag_cate");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long dicdiagcateId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(dicdiagcateId);
                		cdcDictionaryEntity.setCode(busdiagcatecode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long busdiagcateid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(dicdiagcateId);
                			cdcDictionaryEntity.setCode(busdiagcatecode);
                			cdcDictionaryEntity.setDescription(busdiagcatedesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			busdiagcateid = cdcDictionaryEntity.getId();
                		}else {
                			busdiagcateid = cdcDictionaryEntity.getId();
                		}
                		diag.setBusDiagCateId(busdiagcateid);
                	}
                	
                	//获取ID
                	if(CommonUtil.isNotEmpty(busdiagtypecode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                		cdcDictypeEntity.setCode("bus_diag_type");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long dicdiagtypeId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(dicdiagtypeId);
                		cdcDictionaryEntity.setCode(busdiagtypecode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long busdiagtypeid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(dicdiagtypeId);
                			cdcDictionaryEntity.setCode(busdiagtypecode);
                			cdcDictionaryEntity.setDescription(busdiagtypedesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			busdiagtypeid = cdcDictionaryEntity.getId();
                		}else {
                			busdiagtypeid = cdcDictionaryEntity.getId();
                		}
                		diag.setBusDiagTypeId(busdiagtypeid);
                	}
                	
                	if(CommonUtil.isNotEmpty(description)) {
                		diag.setDescription(description);
                	}
                	if(CommonUtil.isNotEmpty(icd10)) {
                		diag.setIcd10(icd10);
                	}
                	if(CommonUtil.isNotEmpty(ismainstr)) {
                		Integer ismain = Integer.valueOf(ismainstr);
                		diag.setIsMain(ismain);
                	}
                	//获取ID
                	if(CommonUtil.isNotEmpty(busdiagstatuscode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                		cdcDictypeEntity.setCode("bus_diag_status");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long dicdiagstatusId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(dicdiagstatusId);
                		cdcDictionaryEntity.setCode(busdiagstatuscode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long busdiagstatusid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(dicdiagstatusId);
                			cdcDictionaryEntity.setCode(busdiagstatuscode);
                			cdcDictionaryEntity.setDescription(busdiagstatusdesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			busdiagstatusid = cdcDictionaryEntity.getId();
                		}else {
                			busdiagstatusid = cdcDictionaryEntity.getId();
                		}
                		diag.setBusDiagStatusId(busdiagstatusid);
                	}
                	if(CommonUtil.isNotEmpty(diagdatestr)) {
                		Date diagdate = sdf.parse(diagdatestr);
                		diag.setDiagDate(diagdate);
                	}
                	if(CommonUtil.isNotEmpty(attackdatestr)) {
                		Date attackdate = sdf.parse(attackdatestr);
                		diag.setAttackDate(attackdate);
                	}
                	//获取ID
                	if(CommonUtil.isNotEmpty(busdiagsourcecode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                		cdcDictypeEntity.setCode("bus_diag_source");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long dicdiagsourceId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(dicdiagsourceId);
                		cdcDictionaryEntity.setCode(busdiagsourcecode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long busdiagsourceid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(dicdiagsourceId);
                			cdcDictionaryEntity.setCode(busdiagsourcecode);
                			cdcDictionaryEntity.setDescription(busdiagsourcedesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			busdiagsourceid = cdcDictionaryEntity.getId();
                		}else {
                			busdiagsourceid = cdcDictionaryEntity.getId();
                		}
                		diag.setBusDiagSourceId(busdiagsourceid);
                	}
                	if(CommonUtil.isNotEmpty(note)) {
                		diag.setNote(note);
                	}
            		diag.setDataId(dataId);
                	diag.setIsActive(1);
                }else {
                	diag.setIsActive(0);
                }
                //先判断是不是有该对象
                Wrapper<CdcDiagnosisEntity> wrapper =  new EntityWrapper<CdcDiagnosisEntity>();
                wrapper.eq("xcode", diag.getXcode());
                wrapper.eq("data_id", dataId);
                int count = this.selectCount(wrapper);
                if(count>0) {
                	this.update(diag, wrapper);
                }else {
                	this.insert(diag);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        } catch (Exception e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        }
		return "<response><status>1</status><message>ok</message></response>";
	}

	@Override
	public List<CdcDiagnosisEntity> selectDiagInfo(Long episodeId, Long diagSource, Long diagType) {
		Map param = new HashMap();
		param.put("episodeId", episodeId);
		param.put("diagSource", diagSource);
		param.put("diagType", diagType);
		return this.baseMapper.selectDiagInfo(param);
	}

	@Override
	public List<CdcDiagnosisEntity> selectDiagInfoByParam(Long episodeId, Long diagSource, Long diagType, String filterTxt, String keywordAndTxt, String keywordOrTxt) {
		return this.baseMapper.selectDiagInfoByParam(episodeId, diagSource, diagType, filterTxt, keywordAndTxt, keywordOrTxt);
	}

}